package fun.taostool.config;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.annotation.Resource;
import javax.sql.DataSource;

/**
 * TAOS WebSocket 连接
 */
@Slf4j
@Configuration
@MapperScan(basePackages = {"fun.taostool.mapper.tdengine"}, sqlSessionTemplateRef = "tdengineSqlSessionTemplate")
public class TaosDataSourceConfig {

    @Resource
    private ProjectConfig projectConfig;

    @Primary
    @Bean(name = "tdengineDataSource")
    public DataSource tdengineDataSource() {
        HikariConfig hikariConfig = new HikariConfig();
        String url = projectConfig.getTdWebSocketUrl();
        String user = projectConfig.getTdWebSocketUsername();
        String password = projectConfig.getTdWebSocketPassword();
        if (projectConfig.getLinkType().equals("ws")) {
            log.info("准备使用WebSocket方式链接Taos...");
            hikariConfig.setDriverClassName("com.taosdata.jdbc.ws.WebSocketDriver");
            hikariConfig.setJdbcUrl("jdbc:TAOS-WS://" + url + "?user=" + user + "&password=" + password + "&charset=UTF-8&useSSL=false");
        } else {
            log.info("准备使用Restful方式链接Taos...");
            hikariConfig.setDriverClassName("com.taosdata.jdbc.rs.RestfulDriver");
            hikariConfig.setJdbcUrl("jdbc:TAOS-RS://" + url + "?user=" + user + "&password=" + password + "&charset=UTF-8&useSSL=false");
        }
        hikariConfig.setPoolName("TDengineHikariCP");
        hikariConfig.setMinimumIdle(10);           //minimum number of idle connection
        hikariConfig.setMaximumPoolSize(10);      //maximum number of connection in the pool
        hikariConfig.setConnectionTimeout(1000); //maximum wait milliseconds for get connection from pool
        hikariConfig.setValidationTimeout(300);
        hikariConfig.setMaxLifetime(0);       // maximum life time for each connection
        hikariConfig.setIdleTimeout(0);       // max idle time for recycle idle connection
        hikariConfig.setConnectionTestQuery("select server_status()");
        DataSource hikariDataSource = new HikariDataSource(hikariConfig);
        return hikariDataSource;
    }


    @Primary
    @Bean(name = "tdengineSqlSessionFactory")
    public SqlSessionFactory tdengineSqlSessionFactory(@Qualifier("tdengineDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
//        bean.setPlugins(new Interceptor[]{mybatisInterceptor});
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/tdengine/*.xml"));
        return bean.getObject();
    }

    @Primary
    @Bean(name = "tdengineTransactionManager")
    public DataSourceTransactionManager tdengineTransactionManager(@Qualifier("tdengineDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Primary
    @Bean(name = "tdengineSqlSessionTemplate")
    public SqlSessionTemplate tdengineSqlSessionTemplate(@Qualifier("tdengineSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Primary
    @Bean("taosJdbcTemplate")
    public JdbcTemplate jdbcTemplate(@Qualifier("tdengineDataSource") DataSource dataSource) {
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        jdbcTemplate.setDataSource(dataSource);
        jdbcTemplate.setFetchSize(1000);
        jdbcTemplate.setLazyInit(false);
        return jdbcTemplate;
    }
}

